import csv
import re
from collections import defaultdict

# 解析每一行
def parse_row(line):
    parts = line.strip().split(',')
    if len(parts) < 9:  # 因为现在有 7 列
        return None
    # 使用车辆名称、悬架高度、路面、前后系统、障碍物名称 作为唯一标识符
    vehicle_name = parts[1]
    suspension_height = parts[2]
    road = parts[3]
    obj_name = parts[4]
    highlabel = parts[5]
    od_dir = int(parts[6])
    test_nums = parts[7]
    direction = "unknow"
    if od_dir == 1:
        direction = "front"
    elif od_dir == 2:
        direction = "rear"

    # direction = od_dir
    values = list(map(int, re.findall(r'\d+', parts[8])))  # 假设探测范围是最后一列

    key = (vehicle_name, suspension_height, road, obj_name, highlabel, direction, test_nums)  # 唯一标识符

    return key, direction, values

# 按断开分段
def segment_by_disconnection(frames, invalid_val=5100):
    segments = []
    current = []

    # 跳过前面连续为5100的帧
    i = 0
    while i < len(frames) and all(v == invalid_val for v in frames[i]):
        i += 1

    for frame in frames[i:]:
        if all(v == invalid_val for v in frame):
            if current:
                segments.append(current)
                current = []
        else:
            current.append(frame)

    if current:
        segments.append(current)

    return segments

# 过滤数据段
def filter_segment(segment, max_valid_val):
    return [
        [v for v in frame if v <= max_valid_val]
        for frame in segment
    ]

# 获取段的最大值和最小值
def get_range_for_segment(segment, direction, invalid_val=5100):
    flat = [v for frame in segment for v in frame if v != invalid_val]  

    if direction == "front":
        flat = [v for v in flat if v <= 1200]
    elif direction == "rear":
        flat = [v for v in flat if v <= 1500]
    
    if not flat:
        return None

    return max(flat), min(flat)

# 处理数据
def process_data(input_lines):
    obj_data = defaultdict(list)

    for line in input_lines:
        parsed = parse_row(line)
        if parsed:
            key, direction, values = parsed
            obj_data[key].append(values)

    output_rows = []
    for key, frames in obj_data.items():
        # 分段并计算范围
        segments = segment_by_disconnection(frames)
        filtered_ranges = []
        prev_min = float('inf')

        for idx, seg in enumerate(segments):
            if idx > 0:
                seg = filter_segment(seg, prev_min)

            r = get_range_for_segment(seg,key[5])
            if r is None:
                continue
            seg_max, seg_min = r
            prev_min = seg_min

            # if key[5] == "front":
            #     seg_max = min(seg_max, 1200)  # 单位为毫米×10
                # if (seg_max > 1200):
                    # continue
            # elif key[5] == "rear":
            #     seg_max = min(seg_max, 1500)
                # if (seg_max > 1500):
                #     continue

            if seg_min > seg_max:
                continue  # 跳过该段（非法）
            if seg_max <=310:
                continue

            if seg_min < 310:
                min_str = "红区"
            else:
                min_str = f"{seg_min // 10}"
            filtered_ranges.append(f"[{seg_max//10}-{min_str}]")

        if not filtered_ranges:
            range_combined = "无报警"
        else:
            range_combined = '、'.join(filtered_ranges)

        # 拼接唯一标识符和最终结果
        output_rows.append(list(key) + [range_combined])

    return output_rows

# 保存结果到CSV文件
def save_csv(output_path, rows):
    header = ['车辆名称', '悬架高度', '路面', '障碍物名称','高低标签','前后系统', '测试次数','检测距离段']
    with open(output_path, 'w', newline='', encoding='utf-8-sig') as f:  # UTF-8 BOM 防乱码
        writer = csv.writer(f)
        writer.writerow(header)
        writer.writerows(rows)

# 主程序
def process_csv_log(input_path):
    input_file = input_path
    output_file = "processed_segments.csv"

    with open(input_file, 'r', encoding='utf-8') as f:
        lines = f.readlines()[1:]  # 跳过原始文件第一行表头

    result = process_data(lines)
    save_csv(output_file, result)
    return output_file
    # print(f"✅ 已完成，输出文件为：{output_file}")



# if __name__ == "__main__":
#     input_file = r"D:\Project\tool_process_pdc\Save_OD.csv"
#     output_file = "processed_segments.csv"

#     with open(input_file, 'r', encoding='utf-8') as f:
#         lines = f.readlines()[1:]  # 跳过原始文件第一行表头

#     result = process_data(lines)
#     save_csv(output_file, result)
#     print(f"✅ 已完成，输出文件为：{output_file}")
